#!/bin/sh

e2e_test_install() {
  RESTORED_CLUSTER_NAME="$(get_sgcluster_name restored-from-aks)"
  ACCOUNT_KEY="$(az storage account keys list --account-name "$K8S_AZ_K8S_NAME" \
    --resource-group "$K8S_AZ_RESOURCE_GROUP" --output tsv \
    | grep key1 | awk '{print $3}')"
  
  echo "checking if container exists"
  if az storage container show --name "$CLUSTER_NAME" \
   --account-key "$ACCOUNT_KEY" \
   --account-name "$K8S_AZ_K8S_NAME" \
   --name "$CLUSTER_NAME" > /dev/null 
  then
    az storage container delete --account-key "$ACCOUNT_KEY" \
      --account-name "$K8S_AZ_K8S_NAME" \
      --name "$CLUSTER_NAME"
  fi  

  wait_until eval '[ $(create_az_container) != "False" ]'
 
  kubectl create namespace "$CLUSTER_NAMESPACE"

  kubectl create secret generic storage-account \
    -n "$CLUSTER_NAMESPACE" \
    --from-literal=account="$K8S_AZ_K8S_NAME" \
    --from-literal=accessKey="$ACCOUNT_KEY"

  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 1 \
    --set-string cluster.configurations.shBackupConfig=backupconf

  wait_pods_running "$CLUSTER_NAMESPACE" 1
  wait_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"

  create_mock_data

  BACKUP_NAME="$(get_sgbackup_name "${CLUSTER_NAME}-0-$(shuf -i 0-65535 -n 1)")"
}

e2e_test_uninstall(){
  helm_cleanup_chart "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"

  k8s_async_cleanup_namespace "$CLUSTER_NAMESPACE"

  ACCOUNT_KEY="$(az storage account keys list --account-name "$K8S_AZ_K8S_NAME" \
    --resource-group "$K8S_AZ_RESOURCE_GROUP" --output tsv \
    | grep key1 | awk '{print $3}')"

  az storage container delete --account-key "$ACCOUNT_KEY" \
      --account-name "$K8S_AZ_K8S_NAME" \
      --name "$CLUSTER_NAME"
}

e2e_test() {
  run_test "Check that backup is executed successfully" execute_backup

  run_test "Check that restoration is executed successfully" restore_from_backup

  run_test "Check restored data integrity" check_restored_data

}

create_az_container() {
  CONTAINER_CREATED="$(az storage container create --name "$CLUSTER_NAME" \
    --account-key "$ACCOUNT_KEY" \
    --account-name "$K8S_AZ_K8S_NAME" --output tsv)"
  echo "$CONTAINER_CREATED"
}

create_mock_data() {
  run_query -p 5432 -h "$CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" -c "$CLUSTER_NAME" -q "CREATE DATABASE test;"
  run_query -p 5432 -h "$CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" -c "$CLUSTER_NAME" -q "CREATE TABLE fibonacci(num integer);" -d "test"
  run_query -p 5432 -h "$CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" -c "$CLUSTER_NAME" -q "INSERT INTO fibonacci(num) VALUES (1);" -d "test"
  run_query -p 5432 -h "$CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" -c "$CLUSTER_NAME" -q "INSERT INTO fibonacci(num) VALUES (2);" -d "test"
  run_query -p 5432 -h "$CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" -c "$CLUSTER_NAME" -q "INSERT INTO fibonacci(num) VALUES (3);" -d "test"
}

is_backup_phase() {
  [ "$(kubectl get sgbackup -n "$CLUSTER_NAMESPACE" "$BACKUP_NAME" -o=jsonpath='{.status.process.status}')" = "$1" ]
}


execute_backup() {
  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGBackup
metadata:
  namespace: "$CLUSTER_NAMESPACE"
  name: "$BACKUP_NAME"
spec:
  sgCluster: "$CLUSTER_NAME"
  managedLifecycle: false
EOF
  
  wait_until is_backup_phase "Completed"

  success "Backup completed"
}

restore_from_backup() {
  kubectl delete sgclusters.stackgres.io -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME"

  BACKUP_UID="$(kubectl get sgbackups.stackgres.io -n "$CLUSTER_NAMESPACE" "$BACKUP_NAME" -o=jsonpath='{.metadata.uid}')"

  cat <<EOF | kubectl apply -f -
apiVersion: stackgres.io/v1
kind: SGCluster
metadata:
  name: $RESTORED_CLUSTER_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  instances: 2
  postgres:
    version: "$E2E_POSTGRES_VERSION"
  sgInstanceProfile: size-s
  pods:
    persistentVolume:
      size: '512Mi'
  initialData:
    restore:
      downloadDiskConcurrency: 10
      fromBackup:
        uid: "$BACKUP_UID"
EOF

  wait_pods_running "$CLUSTER_NAMESPACE" 2

  success "Cluster restored from backup $BACKUP_NAME"
}

check_restored_data() {
  REPLICA_RESPONSE="$(run_query -p 5432 -h "$RESTORED_CLUSTER_NAME-replicas" -c "$RESTORED_CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" -i 1 -q "SELECT num FROM fibonacci ORDER BY num;" -d "test")"
  if [ "$(echo "$REPLICA_RESPONSE" | tr -d '\n')" = "123" ]
  then
    success "restore replica db restored successfully"
  else
    fail "replica db not restored"
  fi
}
